package com.mingqijia.gassafety.authority.vcc.user;

import cn.hutool.json.JSONObject;
import com.gap.cache.redis.RedisCache;
import com.mingqijia.gassafety.authority.dal.command.UpdateManagerCommand;
import com.mingqijia.gassafety.authority.vcc.valueobject.VccUserVO;
import com.mingqijia.gassafety.shared.constant.Constants;
import com.mingqijia.gassafety.shared.utils.MappingTools;
import com.mingqijia.gassafety.shared.vcc.VccAuthoritiesProvider;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.time.Instant;
import java.util.concurrent.TimeUnit;

/**
 * 用户信息统一处理类
 *
 * @author Damon S.
 * @version v0.2
 * @date 2022-02-28 18:47
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class VccUserLoginHolder {

    private final RedisCache cacheManager;
    private final VccAuthoritiesProvider provider;
//    private final VccUserTranslator translator;
//    private final ManagerProvider provider;
//    private final CompanyProvider cProvider;

//
//    public ManagerVO findManagerByUsername(String username) {
//        ManagerVO backend;
//        String cachedUserBackend = cacheManager.getCacheObject(
//                String.format(Constants.KEY_MANAGE_PROFILE, username));
//        if (ObjectUtils.isEmpty(cachedUserBackend)) {
//            // 从数据库中取数据
//            backend = translator.toVO(provider.getByUsername(username));
//        } else {
//            // 从缓存中取数据
//            backend = ApplicationUtils.toBean(cachedUserBackend, ManagerVO.class);
//        }
//        if (ObjectUtils.isEmpty(backend)) {
//            throw new GlobalAuthenticationException("用户不存在"+username);
//        }
//        backend.setPassword(null);
//        cacheWorkingUserState(backend);
//        return backend;
//    }
//
//    public void whenWorkingSpIdChanged(String spId) {
//        CompanyEntry entry = cProvider.getById(spId);
//        if (ObjectUtils.isEmpty(entry)) {
//            throw new GlobalAuthenticationException("spId不存在");
//        }
//        // 更新最近使用企业
//        UserBackend backend = ApplicationUtils.getWorkingUser();
//        UpdateManagerCommand command = UpdateManagerCommand.builder()
//                .workingSpId(spId).userId(backend.getUserId()).build();
//        if (!provider.update(command)) {
//            log.error("更新用户信息[user={}, workingSpId={}]失败", backend.getUsername(), spId);
//            throw new GlobalAuthenticationException("系统错误，更新用户信息失败");
//        }
//        ((ManagerVO) backend).setWorkingSpId(spId);
//        // 缓存用户信息
//        cacheWorkingUserState(backend);
//    }
//
//    public void whenManagerUpdated(String userId) {
//        ManagerEntry entry = provider.getById(userId);
//        cacheManager.deleteObject(String.format(Constants.KEY_MANAGE_PROFILE, entry.getUsername()));
//    }

//    public ManagerVO findManagerFromDb(String username) {
//        ManagerEntry backend = provider.getByUsername(username);
//        if (ObjectUtils.isEmpty(backend)) {
//            throw new GlobalAuthenticationException("用户名或密码错误");
//        }
//        return translator.toVO(backend);
//    }

    public JSONObject buildVccUserDetail(VccUserVO backend) {
        // 燃气云方式登录
        JSONObject userDetail = provider.getUserDetail(backend.getToken());
        log.info("获取登录用户信息：{}", userDetail);

        backend.setPhone(userDetail.getStr("contactInfo"));
        backend.setSpId(userDetail.getStr("spId"));
        backend.setUsername(userDetail.getStr("userCode"));
        backend.setName(userDetail.getStr("userName"));
        return userDetail;
    }

    public void whenManagerLogin(VccUserVO backend) {
        UpdateManagerCommand command = UpdateManagerCommand.builder()
                .logoutAt(MappingTools.DEFAULT_MAX_LDT).updatedBy(backend.getUserId())
                .loginAt(MappingTools.getCurrent()).userId(backend.getUserId()).build();
//        if (!provider.update(command)) {
//            throw new GlobalAuthenticationException("更新用户登录信息失败");
//        }
        // 先清一下密码
        backend.setPassword(null);
        backend.setLogoutAt(command.getLogoutAt());
        backend.setLoginAt(command.getLoginAt());

        //本地缓存token提前两分钟失效
        backend.setExpireAt(Instant.now().getEpochSecond() + backend.getExpireTime() - 120);

        // 设置角色
//        List<RoleEntry> entries = rProvider.findValidRoles(backend.getRoleIds());
//        backend.setRoleIds(entries.stream().map(RoleEntry::getId).collect(Collectors.toList()));
        // 缓存用户信息
        cacheWorkingUserState(backend);


        cacheManager.deleteObject(Constants.LOGIN_USER_PERMISSION_REDIS_KEY+":"+backend.getUserId());
    }

    public void whenManagerLogout(VccUserVO backend) {
        // 设置登出时间，再更新数据库用户登出
//        UpdateManagerCommand command = UpdateManagerCommand.builder()
//                .userId(backend.getUserId()).updatedBy(backend.getUserId())
//                .logoutAt(MappingTools.getCurrent()).build();
//        provider.update(command);
        // 更新缓存
//        backend.setLogoutAt(command.getLogoutAt());

        cacheManager.deleteObject(Constants.LOGIN_USER_PERMISSION_REDIS_KEY+":"+backend.getUserId());

        clearCacheWorkingUserState(backend);
    }

    private void clearCacheWorkingUserState(VccUserVO backend) {
//        cacheManager.deleteObject(String.format(Constants.KEY_MANAGE_PROFILE, backend.getUserId()));
//        cacheManager.deleteObject(String.format(Constants.KEY_MANAGE_PROFILE, backend.getUsername()));
        if (Constants.STR_CODE.equals(backend.getLoginType())) {
            //cacheManager.deleteObject(String.format(Constants.KEY_MANAGE_PROFILE, backend.getRefreshToken()));
        } else {
            //cacheManager.deleteObject(String.format(Constants.KEY_MANAGE_PROFILE, backend.getToken()));
        }
    }

    private void cacheWorkingUserState(VccUserVO backend) {
        // 按用户名缓存
//        cacheManager.setCacheObject(String.format(Constants.KEY_MANAGE_PROFILE, backend.getUsername()),
//                backend, backend.getExpireTime(), TimeUnit.SECONDS);
//        // 按openId缓存
//        cacheManager.setCacheObject(String.format(Constants.KEY_MANAGE_PROFILE, backend.getUserId()),
//                backend, backend.getExpireTime(), TimeUnit.SECONDS);
        if (Constants.STR_CODE.equals(backend.getLoginType())) {
            log.info("当前为code登录模式，开启缓存：{}", backend);
            cacheManager.setCacheObject(String.format(Constants.KEY_MANAGE_REFRESH_TOKEN, backend.getToken()),
                    backend.getRefreshToken(), backend.getRefreshTokenExpiration(), TimeUnit.SECONDS);
            // 按refreshToken缓存 （120：本地缓存token提前两分钟失效）
            cacheManager.setCacheObject(String.format(Constants.KEY_MANAGE_PROFILE, backend.getRefreshToken()),
                    backend, backend.getExpireTime() - 120, TimeUnit.SECONDS);

            cacheManager.setCacheObject(String.format(Constants.KEY_MANAGE_PROFILE_CODE, backend.getToken()),
                    backend, backend.getExpireTime() - 120, TimeUnit.SECONDS);
        } else {
            cacheManager.setCacheObject(String.format(Constants.KEY_MANAGE_PROFILE, backend.getToken()),
                    backend, backend.getExpireTime() - 120, TimeUnit.SECONDS);
        }
    }

    private void cacheWorkingUserRefreshedToken(VccUserVO backend) {
        cacheManager.setCacheObject(String.format(Constants.KEY_MANAGE_PROFILE, backend.getToken()),
                backend, backend.getExpireTime(), TimeUnit.SECONDS);
    }
}
